package com.atguigu.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.SpzxException;
import com.atguigu.spzx.model.dto.h5.ProductSkuDto;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.entity.product.Product;
import com.atguigu.spzx.model.entity.product.ProductDetails;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.IndexVo;
import com.atguigu.spzx.model.vo.h5.ProductSkuVo;
import com.atguigu.spzx.model.vo.h5.SpecValueVo;
import com.atguigu.spzx.order.client.OrderClient;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.mapper.ProductDetailsMapper;
import com.atguigu.spzx.product.mapper.ProductMapper;
import com.atguigu.spzx.product.mapper.ProductSkuMapper;
import com.atguigu.spzx.product.service.ProductService;
import com.atguigu.spzx.product.service.ProductSkuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    CategoryMapper categoryMapper;
//    @Resource  //从容器中获取被代理过的自己
//    ProductService productService;
    @Resource
    ProductSkuMapper productSkuMapper;
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductDetailsMapper productDetailsMapper;
    @Resource
    OrderClient orderClient;

    @Override
    public IndexVo findIndexVo() {
        //1、查询一级分类列表
        List<Category> categoryList = categoryMapper.findOneCategories();
        //2、查询按销量排名的前10条sku记录
        List<ProductSku> productSkuList = productSkuMapper.findProductSkusBySales();
        IndexVo indexVo = new IndexVo();
        indexVo.setCategoryList(categoryList);
        indexVo.setProductSkuList(productSkuList);
        return indexVo;
    }

    @Override
    public PageInfo<ProductSku> findPage(Integer pageNum, Integer pageSize, ProductSkuDto productSkuDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductSku> productSkuList = productSkuMapper.findPage(productSkuDto);
        return new PageInfo<>(productSkuList);
    }
    @Cacheable(value = "product:item" , key = "#skuId")
    @Override
    public ProductSkuVo findItemBySkuId(Long skuId) {
        //根据skuid查询sku：  product_sku
        ProductSku productSku = productSkuMapper.findProductSkuById(skuId);
        //根据sku的productId查询product: product
        Product product = productMapper.findProductById(productSku.getProductId());
        //根据productId查询详情图: product_details
        ProductDetails productDetails = productDetailsMapper.findProductDetailsById(productSku.getProductId());
        //根据productId查询sku列表: product_sku
        List<ProductSku> productSkuList = productSkuMapper.findProductSkusByProductId(productSku.getProductId());

        //组装数据：
        ProductSkuVo productSkuVo = new ProductSkuVo();
        productSkuVo.setProductSku(productSku);
        productSkuVo.setProduct(product);
        //轮播图列表
        productSkuVo.setSliderUrlList(
                //如果SliderUrls属性不为空，使用逗号分隔为字符串数组后转为List集合
                StringUtils.isEmpty(product.getSliderUrls())?null
                :Arrays.asList(product.getSliderUrls().split(",")) );
        //详情图列表
        List<String>  detailsImageUrlList = StringUtils.isEmpty(productDetails.getImageUrls())?
                null:Arrays.asList(productDetails.getImageUrls().split(","));
        productSkuVo.setDetailsImageUrlList(detailsImageUrlList);
        //product的商品规格可选值列表
        List<SpecValueVo> specValueVos = JSON.parseArray(product.getSpecValue(), SpecValueVo.class);
        productSkuVo.setSpecValueList(specValueVos);
        //sku规格属性值 映射sku的id
        Map<String, Long> map = productSkuList.stream()
                .collect(Collectors.toMap(ProductSku::getSkuSpec, ProductSku::getId));
        productSkuVo.setSkuSpecValueMap(map);
        return productSkuVo;
    }

    @Override
    public ProductSku findSkuById(Long skuId) {
        return productSkuMapper.findProductSkuById(skuId);
    }
    @Resource
    ProductSkuService productSkuService;
    @Override
    public void updateSkuSalesAndStockByOrderNo(String orderNo) {
        //1、使用orderNo查询 orderItem列表
        Result<OrderInfo> result = orderClient.findOrderByOrderNo(Long.parseLong(orderNo));
        if(result.getCode()!=200){
            throw new SpzxException(ResultCodeEnum.ERROR , null);
        }
        List<OrderItem> orderItemList = result.getData().getOrderItemList();
        //2、根据orderItem列表中的 skuId  和 skuNum 更新 sku的销量和库存
        orderItemList.forEach(orderItem -> {
            //this没有被代理  所有基于aop的缓存管理会失效
            productSkuService.updateSkuStockAndSales(orderItem);
        });



    }
    //spring 动态代理问题：
    //驱逐缓存

}
